package consul

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"week_one/user_srv/common/global"
)

type RegistryConsul struct {
	Host string
	Port int
}
type RegistryClient interface {
	RegisterConsul(id string, name string, tags []string) error
	FilterConsulById(name string) (map[string]*api.AgentService, error)
	Deregister(id string) error
}

func NewRegistryClient(host string, port int) RegistryClient {
	return &RegistryConsul{
		Host: host,
		Port: port,
	}
}
func (c *RegistryConsul) RegisterConsul(id string, name string, tags []string) error {
	return global.ConsulClient.Agent().ServiceRegister(&api.AgentServiceRegistration{
		ID:      id,
		Name:    name,
		Tags:    tags,
		Port:    c.Port,
		Address: c.Host,
		Check: &api.AgentServiceCheck{
			Interval: "3s",
			GRPC:     fmt.Sprintf("%s:%d", c.Host, c.Port),
		},
	})
}
func (c *RegistryConsul) FilterConsulById(name string) (map[string]*api.AgentService, error) {
	return global.ConsulClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, name))
}
func (c *RegistryConsul) Deregister(id string) error {
	return global.ConsulClient.Agent().ServiceDeregister(id)
}
